import {TYSdk, Utils} from "tuya-panel-kit";
import {commonApi} from "@tuya/tuya-panel-api";
import Res from "../res";
import dpCodes from "../config/dpCodes";
import Strings from "../i18n";



/**
 * 获取设备激活所在地的空气质量信息
 */
TYSdk.getWeatherQuality = () => {
  return new Promise((resolve, reject) => {
    console.log('获取设备激活所在地的空气质量信息');
    TYSdk.device.getDeviceInfo().then(res => {
      const { devId } = res;
      TYSdk.apiRequest(
        'tuya.m.public.weather.get',
        {
          devId,
          codes: [
            'city.id',
            'city.name',
            'weather.air.qualityLevel',
            'weather.air.pm25',
            'weather.air.quality',
            'weather.now.temperature',
            'weather.now.hum',
            'weather.now.condIconUrl',
            'weather.now.condTxt',
          ],
        },
        '1.0'
      )
        .then(d => {
          const data = Utils.JsonUtils.parseJSON(d);
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  });
};

TYSdk.getDeviceInfo = () => {
  TYSdk.device
    .getDeviceState()
    .then(data => {
      console.log('data :>> ', data);
    })
    .catch(error => {
      console.log('error :>> ', error);
    });
};

// 获取定时列表
TYSdk.getTimerList = (timerType) => {
  const type = timerType === 'light' ? 'light' : 'feed';
  return new Promise((resolve, reject) => {
    console.log('获取定时列表');
    // TYSdk.devInfo.devId
    TYSdk.device.getDeviceInfo().then(res => {
      const { devId, groupId } = res;
      commonApi.timerApi
        .queryTimerTasks({
          bizId: groupId || devId,
          bizType: groupId ? '1' : '0',
          category: type,
        })
        .then(response => {
          console.log(response);
          const { timers } = response;
          // console.log(timers);

          // 将数组中具有相同id属性的对象合并到一个新对象中
          const merged = [];
          const map = {};
          timers.forEach((item) => {
            const existing = map[item.groupId];
            if (existing) {
              existing.endTime = item.time;
              existing.endTimeDps = item.dps;
              existing.endTimeId = item.id;
            } else {
              map[item.groupId] = { ...item, groupId: item.groupId };
              merged.push(map[item.groupId]);
            }

            if (timerType === 'light'){
              // 模式
              const dps = TYSdk.jsonToDict(item.dps);
              const lightSwitch = dps['1'];
              let mode;
              let modeTitle = '';
              if (lightSwitch) {
                mode = dps['5'];

                lightMode.map((item) => {
                  if (item.value === mode){
                    modeTitle = item.title;
                  }
                })
              }else {
                mode = 'close';
                modeTitle = Strings.light_mode_title_off;
              }
              item.name = modeTitle;
            }else {
              // 份数
            }
          });

          // 用于新建定时时判断参数是否与列表中的一致，一样的参数不能重复添加定时
          merged.forEach(item => {
            // '[{"dps":{"1":true,"5":"Color1"},"time":"18:00"},{"dps":{"1":false},"time":"18:05"}]'
            const endTime = item.endTime ? ',{"dps":'+item.endTimeDps+',"time":"'+item.endTime+'"}' : '';
            const timerString = item.loops+'[{"dps":'+item.dps+',"time":"'+item.time+'"}'+endTime+']';
            item.timerString = timerString;
          })

          // console.log('merged', merged);

          resolve(merged);
        })
        .catch(error => {
          reject(error);
        });
    });
  });
};

// 获取喂食记录列表
TYSdk.getFeedRecordList = () => {

  return new Promise((resolve, reject) => {
    commonApi.statApi
      .getDpReportLog({
        devId: TYSdk.devInfo.devId,
        dpIds: "150", // 多个DP
        offset: 0,
        limit: 30,
        sortType: "DESC"
      })
      .then(response => {
        // [{timeStamp: 1716518224, value: '16842753', dpId: 150, timeStr: '2024-05-24 10:37:04'}]
        let list = response.dps;

        list.forEach((item) => {
          let valueHexString = parseInt(item.value, 10).toString(16);
          if (valueHexString.length < 7) {
            console.log("喂食记录数据解析出差", valueHexString);
          } else if (valueHexString.length < 8) {
            // 字符串前面补0，8是目标长度
            valueHexString = valueHexString.padStart(8, "0");
          }

          let targetCount = valueHexString.slice(0, 2);
          let successCount = valueHexString.slice(2, 4);
          let feedState = valueHexString.slice(4, 6);
          let todayCount = valueHexString.slice(6, 8);

          // console.log('十进制字符串', valueHexString);
          // console.log('截取字符串', targetCount,successCount,feedState,todayCount);

          targetCount = parseInt(targetCount, 16).toString();
          successCount = parseInt(successCount, 16).toString();
          feedState = parseInt(feedState, 16).toString();
          todayCount = parseInt(todayCount, 16).toString();

          let name = "";
          let count = Strings.formatValue('feeding_record_value', successCount);//"已喂" + successCount + "份";
          if (feedState === "0") {
            name = Strings.feeding_record_title_success;//"喂食成功";
          } else if (feedState === "2") {
            name = Strings.feeding_record_title_power_turned_off;//"喂食失败（设备关机）";
          } else {
            name = Strings.feeding_record_title_timeout;//"喂食失败（故障）";
          }
          item.name = name;
          item.count = count;
        });
        console.log("喂食列表数据 list", list);
        resolve(list);
      })
      .catch(error => {
        reject(error);
      });
  });
};

// 灯光模式列表
TYSdk.getLightModeList = () => {

  const modeString =  TYSdk.device.getState("light_mode_list");
  const curMode = TYSdk.device.getState("work_mode");
  const doNotDisturbLightSwitch = TYSdk.device.getState("light_status_on");// 勿扰模式 灯光开关
  const doNotDisturbLightMode = TYSdk.device.getState("light_status_mode");// 勿扰模式 灯光模式


  const modeArray = modeString.split(",");
  let modeData = [];

  for (let i = 0; i < modeArray.length; i++) {
    let modelength = modeArray[i].length;
    if (modelength === 1) {
      // 默认模式
      let obj;
      switch (modeArray[i]) {
        case "0":
          obj = {
            key: '0',
            title: Strings.light_mode_title_sun,//'日光',
            work_mode: 'Day',
            value: 'Day',// 作为弹窗选项数据时用到
            selected: curMode === 'Day',
            icon: Res.fmode5,
            isBind: TYSdk.checkModeIsBind('Day'),// 灯光模式删除时检查是否被绑定
            string: modeArray[i],// 发送给鱼缸的模式列表内容
          };
          modeData.push(obj);
          break;
        case "1":
          obj = {
            key: '1',
            title: Strings.light_mode_title_flow,//'流光',
            work_mode: 'Flow',
            value: 'Flow',
            selected: curMode === 'Flow',
            icon: Res.fmode6,
            isBind: TYSdk.checkModeIsBind('Flow'),
            string: modeArray[i],
          };
          modeData.push(obj);
          break;
        case "2":
          obj = {
            key: '2',
            title: Strings.light_mode_title_water_grass,//'水草灯',
            work_mode: 'Grass',
            value: 'Grass',
            selected: curMode === 'Grass',
            icon: Res.fmode7,
            isBind: TYSdk.checkModeIsBind('Grass'),
            string: modeArray[i],
          };
          modeData.push(obj);
          break;
        case "7":
          obj = {
            key: '7',
            title: Strings.light_mode_title_night,//"夜灯模式",
            work_mode: 'Night',
            value: 'Night',
            selected: curMode === 'Night',
            icon: Res.fmode4,
            isBind: TYSdk.checkModeIsBind('Night'),
            string: modeArray[i],
          };
          modeData.push(obj);
          break;
        default:
          break;
      }
    } else {
      // 自定义模式
      let getCustom = modeArray[i].split("-");
      // console.log("自定义模式数据", getCustom);
      let obj;
      if (getCustom[2] === '3') {
        obj = {
          key: '3',
          title: Strings.light_mode_title_white,//'白光',
          work_mode: 'Color1',
          value: 'Color1',
          selected: curMode === 'Color1',
          icon: Res.fmode3,
          isBind: TYSdk.checkModeIsBind('Color1'),
          string: modeArray[i],
        };
        modeData.push(obj);
      } else if (getCustom[2] === '4') {
        obj = {
          key: '4',
          title: Strings.light_mode_title_nmg,//'南美风',
          work_mode: 'Color2',
          value: 'Color2',
          selected: curMode === 'Color2',
          icon: Res.fmode1,
          isBind: TYSdk.checkModeIsBind('Color2'),
          string: modeArray[i],
        };
        modeData.push(obj);
      } else if (getCustom[2] === '5') {
        obj = {
          key: '5',
          title: Strings.light_mode_title_xlg,//'溪流风',
          work_mode: 'Color3',
          value: 'Color3',
          selected: curMode === 'Color3',
          icon: Res.fmode2,
          isBind: TYSdk.checkModeIsBind('Color3'),
          string: modeArray[i],
        };
        modeData.push(obj);
      } else if (getCustom[2] === '6') {

        let colorHexString = parseInt(getCustom[0], 10).toString(16);// 10进制字符串转16进制字符串
        // 字符串前面补0，6是目标长度
        colorHexString = '#' + colorHexString.padStart(6, '0');

        obj = {
          key: '6',
          title: getCustom[1],
          work_mode: 'Color4',
          value: 'Color4',
          selected: curMode === 'Color4',
          color: colorHexString,
          isBind: TYSdk.checkModeIsBind('Color4'),
          string: modeArray[i],
          lightSet: getCustom[3],
          modeRGB: getCustom[0],
        };
        modeData.push(obj);
      } else if (getCustom[2] === '8') {

        let colorHexString = parseInt(getCustom[0], 10).toString(16);// 10进制字符串转16进制字符串
        // 字符串前面补0，6是目标长度
        colorHexString = '#'+ colorHexString.padStart(6, '0');

        obj = {
          key: '8',
          title: getCustom[1],
          work_mode: 'Color5',
          value: 'Color5',
          selected: curMode === 'Color5',
          color: colorHexString,
          isBind: TYSdk.checkModeIsBind('Color5'),
          string: modeArray[i],
          lightSet: getCustom[3],
          modeRGB: getCustom[0],
        };
        modeData.push(obj);
      } else if (getCustom[2] === '9') {

        let colorHexString = parseInt(getCustom[0], 10).toString(16);// 10进制字符串转16进制字符串
        // 字符串前面补0，6是目标长度
        colorHexString = '#'+ colorHexString.padStart(6, '0');

        obj = {
          key: '9',
          title: getCustom[1],
          work_mode: 'Color6',
          value: 'Color6',
          selected: curMode === 'Color6',
          color: colorHexString,
          isBind: TYSdk.checkModeIsBind('Color6'),
          string: modeArray[i],
          lightSet: getCustom[3],
          modeRGB: getCustom[0],
        };
        modeData.push(obj);

      } else if (getCustom[2] === '10') {

        let colorHexString = parseInt(getCustom[0], 10).toString(16);// 10进制字符串转16进制字符串
        // 字符串前面补0，6是目标长度
        colorHexString = '#'+ colorHexString.padStart(6, '0');

        obj = {
          key: '10',
          title: getCustom[1],
          work_mode: 'Color7',
          value: 'Color7',
          selected: curMode === 'Color7',
          color: colorHexString,
          isBind: TYSdk.checkModeIsBind('Color7'),
          string: modeArray[i],
          lightSet: getCustom[3],
          modeRGB: getCustom[0],
        };
        modeData.push(obj);

      } else if (getCustom[2] === '11') {

        let colorHexString = parseInt(getCustom[0], 10).toString(16);// 10进制字符串转16进制字符串
        // 字符串前面补0，6是目标长度
        colorHexString = '#'+ colorHexString.padStart(6, '0');

        obj = {
          key: '11',
          title: getCustom[1],
          work_mode: 'Color11',
          value: 'Color11',
          selected: curMode === 'Color11',
          color: colorHexString,
          isBind: TYSdk.checkModeIsBind('Color11'),
          string: modeArray[i],
          lightSet: getCustom[3],
          modeRGB: getCustom[0],
        };
        modeData.push(obj);

      }
    }
  }


  lightMode = modeData;

  return modeData;
};

let lightMode = [];

// 0：没有被绑定 1：被勿扰模式绑定
TYSdk.checkModeIsBind = (mode) => {
  const doNotDisturbLightSwitch = TYSdk.device.getState("light_status_on");// 勿扰模式 灯光开关
  const doNotDisturbLightMode = TYSdk.device.getState("light_status_mode");// 勿扰模式 灯光模式
  const isBind = !doNotDisturbLightSwitch ? '' : doNotDisturbLightMode === mode ? Strings.mode_busy_no_disturb_message : '';//'此模式被勿扰模式绑定，无法删除' : '';
  return isBind;
}

// 首页要显示的灯光模式列表，不够4个补齐4个数据，超过4个不够8个的，补齐8个，用于UI显示占位
TYSdk.getHomeLightModeList = () =>{

  let modeData = [];
  modeData = TYSdk.getLightModeList();
  // 关机、灯光关闭时，不能点击模式
  const enable = !!(TYSdk.device.getState("switch_led") && TYSdk.device.getState("fishtank_switch"));
  // console.log('灯光 enable', enable);
  modeData.forEach((item) => {
    item.onPress = () => {
      if (enable) {
        TYSdk.modeClicked(item.work_mode);
      }
    };
  });

    if (modeData.length < 4) {
      const mode4 = {
        key: '14',
        title: ' ',
      };
      modeData.push(mode4);
    } else if ( modeData.length > 4 && modeData.length < 8) {
      for (let i = modeData.length; i < 8; i++) {
        const mode = {
          key: '2'+i,
          title: ' ',
        };
        modeData.push(mode);
      }
    }

    // console.log('getHomeLightModeList', modeData);

    return modeData;
}

TYSdk.modeClicked = (v) => {
  console.log('模式', v);
  const {
    work_mode: work_modeCode,
  } = dpCodes;

  TYSdk.device.putDeviceData({
    [work_modeCode]: v,
  }).then(r => {});
}

TYSdk.repeatData = () =>{

  return [
    {
      key: '1',
      title: Strings.repeat_value_only_once,//'执行一次',
      value: '1',
    },
    {
      key: '2',
      title: Strings.repeat_value_everyday,//'每天',
      value: '2',
    },
    {
      key: '3',
      title: Strings.repeat_value_custom,//'自定义',
      value: '3',
    },
  ];
}

TYSdk.timerName = (aliasName) => {

  const result = aliasName.split('-');
  // console.log('timerName', result);
  if (result.length === 2) {
    return result[1];
  }else{
    return result[0];
  }
}

TYSdk.repeatWeekData = () =>{

  return [
    {
      key: '1',
      title: Strings.weekday_monday,//'星期一',
      value: '1',
    },
    {
      key: '2',
      title: Strings.weekday_tuesday,//'星期二',
      value: '2',
    },
    {
      key: '3',
      title: Strings.weekday_wednesday,//'星期三',
      value: '3',
    },
    {
      key: '4',
      title: Strings.weekday_thursday,//'星期四',
      value: '4',
    },
    {
      key: '5',
      title: Strings.weekday_friday,//'星期五',
      value: '5',
    },
    {
      key: '6',
      title: Strings.weekday_saturday,//'星期六',
      value: '6',
    },
    {
      key: '7',
      title: Strings.weekday_sunday,//'星期日',
      value: '7',
    },
  ];
}

// 将0100000字符串转换成周一
TYSdk.changeToWeekdays = (binaryString) => {

  if (binaryString === '1111111') {
    return Strings.repeat_value_everyday;//'每天';
  }

  if (binaryString === '0000000') {
    return Strings.repeat_value_only_once;//'执行一次';
  }

  // 移除字符串的第一个字符并追加到末尾
  let string =  binaryString.slice(1) + binaryString.charAt(0);

  let weekdays = [];
  for (let i = 0; i < string.length; i++) {
    if (string[i] === '1') {
      weekdays.push(i + 1); // 将数字转换为对应的周几
    }
  }

  //[ '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const daysOfWeek = [ Strings.weekday_mon, Strings.weekday_tues, Strings.weekday_wed, Strings.weekday_thur, Strings.weekday_fri, Strings.weekday_sat, Strings.weekday_sun];
  const week = weekdays.map(day => daysOfWeek[day - 1]).join('、');

  return week;
}

// 将0000001字符串转换成周一
TYSdk.doNotDisturbChangeToWeekdays = (binaryString) => {


  // 字符串翻转 0100000
  let binaryString1 = binaryString.split("").reverse().join("");


  if (binaryString1 === '1111111') {
    return Strings.repeat_value_everyday;//'每天';
  }

  if (binaryString1 === '0000000') {
    return Strings.repeat_value_only_once;//'执行一次';
  }

  let weekdays = [];
  for (let i = 0; i < binaryString1.length; i++) {
    if (binaryString1[i] === '1') {
      weekdays.push(i + 1); // 将数字转换为对应的周几
    }
  }

  //[ '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const daysOfWeek = [ Strings.weekday_mon, Strings.weekday_tues, Strings.weekday_wed, Strings.weekday_thur, Strings.weekday_fri, Strings.weekday_sat, Strings.weekday_sun];
  const week = weekdays.map(day => daysOfWeek[day - 1]).join(',');

  return week;
}

TYSdk.doNotDisturbChangeToWeekdays2 = (binaryString) => {


  // 字符串翻转 0100000
  let binaryString1 = binaryString.split("").reverse().join("");


  if (binaryString1 === '1111111') {
    return Strings.repeat_value_everyday;//'每天';
  }

  if (binaryString1 === '0000000') {
    return Strings.repeat_value_only_once;//'执行一次';
  }

  let weekdays = [];
  for (let i = 0; i < binaryString1.length; i++) {
    if (binaryString1[i] === '1') {
      weekdays.push(i + 1); // 将数字转换为对应的周几
    }
  }

  //[ '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const daysOfWeek = [ Strings.weekday_mon, Strings.weekday_tues, Strings.weekday_wed, Strings.weekday_thur, Strings.weekday_fri, Strings.weekday_sat, Strings.weekday_sun];
  const week = weekdays.map(day => daysOfWeek[day - 1]).join('、');

  return week;
}

// 将重复周期多选结果（1267）转换成7位的01字符串（1110001） 最左边星期日、一，最右边是星期六
TYSdk.changeNumToBinaryWeek = (numString) => {

  // 使用sort()方法进行升序排序
  const sortedNumbersArray = numString.sort((a, b) => a - b);

  let result = "";
  for (let i = 1; i <= 7; i++) {
    let exists = false;
    for (const str of sortedNumbersArray) {
      if (str.includes(i.toString())) {
        exists = true;
        break;
      }
    }
    result += exists ? "1" : "0";
  }

  // 把字符串的最后一个字符移动到字符串的最前面 因为第一位是周日
  const lastChar = result.slice(-1); // 获取最后一个字符
  const newStr = result.slice(0, -1); // 去掉最后一个字符
  result = lastChar + newStr; // 拼接新字符串

  return result;
}

// 勿扰模式的周期 右边第一位是星期一 将重复周期多选结果（12）转换成7位的01字符串（0000011）
TYSdk.doNotDisturbChangeNumToBinaryWeek = (numString) => {

  // 使用sort()方法进行升序排序
  const sortedNumbersArray = numString.sort((a, b) => a - b);

  let result = "";
  for (let i = 1; i <= 7; i++) {
    let exists = false;
    for (const str of sortedNumbersArray) {
      if (str.includes(i.toString())) {
        exists = true;
        break;
      }
    }
    result += exists ? "1" : "0";
  }
  // 1100000

  // 字符串翻转
  result = result.split("").reverse().join("");

  return result;
}

// 将JSON字符串转换为字典
TYSdk.jsonToDict = (jsonString) => {

  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.error("Error parsing JSON string: ", error);
    return null;
  }
}

// 小时转天数，滤材界面用
TYSdk.hoursToDays = (hours) => {
  console.log('hours', hours)
  let days = 0;
  if (hours === 0) {
    return 0;
  }else {
    days = Math.floor(hours / 24); // 先进行除法运算得到天数的整数部分
    const hour = hours % 24; // 计算小时数对24的余数
    if (days === 0 && hour > 0) {
      days = 1;
    }
  }
  console.log('days', days)
  return days;
}

export default TYSdk;
